
const sha1 = require('sha1');
const crypto = require("crypto");
const Router = require('koa-router');
const axios = require('axios');
const wxRouter = new Router();

const getToken = async (appId, secret) => {
    // &secret=${secret}
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secret}`
    const { data } = await axios(url)
    console.log('token',data)
    return data.access_token
}
const getTicket = async (access_token) => {
    let url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`
    const { data } = await axios(url)
    return data.ticket
}
const getSha1 = (str) =>{
    let sha1 = crypto.createHash("sha1"); //定义加密方式:md5不可逆,此处的md5可以换成任意hash加密的方法名称；
    sha1.update(str);
    let res = sha1.digest("hex"); //加密后的值d
    console.log(1,res)
    return res
}
wxRouter.get('/wx/getSignature', async (ctx) => {
    let timestamp = parseInt(Date.now() / 1000)
    // if (ctx.session.timestamp + 900 <= timestamp || !ctx.session.signature) {
    if (true) {
        // let appId = 'wx1d21ec5801a949a9', secret = '43d6df2a6ccb281bf9cdcf3b84a5766b';
        let appId = 'wxa9765b04b41d156f', secret = '02efde2ec3e16af18adba82f6d215409';
        let nonceStr = Math.random().toString(36).substr(2, 15)
        let token = await getToken(appId, secret);
        let ticket = await getTicket(token);
        // let ticket = `kqxRwT0lF4G-mWsgBWkeInrqDMzNDCxX1nkn5rrmZelaJpE4Oe5YvP41rTxkVD5Lrgu898XWwTsSe_n1HxxQ2w`
        let url = ctx.query.url 
        const params = { nonceStr, jsapi_ticket:ticket, timestamp, url }
        let signString = Object.keys(params).sort().map(key => `${key.toLowerCase()}=${params[key]}`).join('&')
        console.log(333, signString)
        let signature = getSha1(signString)
        let result = {
            appId,
            timestamp,
            nonceStr,
            signature
        }
        // ctx.session = {...result,token}
        // 返回签名信息
        ctx.body = {
            status: 200,
            result
        }
    } else {
        ctx.body = {
            status: 200,
            result: ctx.session
        }
    }



    //     let signature = req.query.signature;
    //     let timestamp = req.query.timestamp;
    //     let nonce = req.query.nonce;
    //     let echostr = req.query.echostr;
    //     console.log(signature, timestamp, nonce, echostr);
    //     let array = new Array(token,timestamp,nonce);
    //     array.sort();
    //     let str = array.toString().replace(/,/g,"");
    //     let sha1Code = crypto.createHash("sha1");
    //     let code = sha1Code.update(str,'utf-8').digest("hex");
    //     if(code===signature){
    //         ctx.body = echostr
    //     }else{
    //         ctx.body = 'error'
    //     }
});


// wxRouter.get('/wx/getSignature', (ctx) => {
//     console.log(23232, ctx)
//     let config = {
//         appID: '',
//         access_token: '',
//         ticket: '',
//         timestamp: '', // 必填，生成签名的时间戳
//         nonceStr: '', // 必填，生成签名的随机串
//         signature: '', // 必填
//     };
//     ctx.body = ({
//         'a': 11
//     })
// });

module.exports = { wxRouter };
